package com.fucheng.transport;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.BufferedOutputStream;
import java.io.ObjectOutputStream;

/**
 * 出站数据编码器：将 RpcRequest / RpcResponse 序列化为字节
 */
public class RpcEncoder extends MessageToByteEncoder<Object> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {

        // 用 ObjectOutputStream 将对象转为字节
        try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(new ByteBufOutputStream(byteBuf))) {
            objectOutputStream.writeObject(msg);
        }
    }
}
